﻿using Aspose.Cells;
using DXApplicationTangche.UC.面料审核.Service;
using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows;

namespace DXApplicationTangche.Utils
{
    public class FileUtil
    {
        /// <summary>
        /// 下载图片
        /// </summary>
        /// <param name="picUrl">图片Http地址</param>
        /// <param name="savePath">保存路径</param>
        /// <param name="timeOut">Request最大请求时间，如果为-1则无限制</param>
        /// <returns>是否下载成功</returns>
        public static bool DownloadPicture(string picUrl, string savePath, int timeOut)
        {
            bool value = false;
            WebResponse response = null;
            Stream stream = null;
            try
            {
                //输入图片url，初始化新的 WebRequest 实例request
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(picUrl);
                if (timeOut != -1) request.Timeout = timeOut;
                //返回网络请求响应
                response = request.GetResponse();
                //从 Internet 资源返回数据流
                stream = response.GetResponseStream();
                //如果发送的请求数据内容类型非text开始，则保存二进制文件
                if (!response.ContentType.ToLower().StartsWith("text/"))
                    //保存二进制文件
                    value = SaveBinaryFile(response, savePath);
            }
            finally
            {
                //关闭流，释放资源
                if (stream != null) stream.Close();
                if (response != null) response.Close();
            }
            return value;
        }
        /// <summary>
        /// 保存二进制文件
        /// </summary>
        /// <param name="response"></param>
        /// <param name="savePath"></param>
        /// <returns></returns>
        private static bool SaveBinaryFile(WebResponse response, string savePath)
        {
            bool value = false;
            byte[] buffer = new byte[1024];
            Stream outStream = null;
            Stream inStream = null;
            try
            {
                //保存路径如果存在该文件，删除
                if (File.Exists(savePath)) File.Delete(savePath);
                //输出流，指定文件路径
                outStream = System.IO.File.Create(savePath);
                //输入流，从 Internet 资源获取数据流
                inStream = response.GetResponseStream();
                int l;
                do
                {
                    //读取字节流里的数据，位置下标从0开始，最多读取buffer.Length个字节的数据，将读取的数据存到buffer缓冲
                    //如果流已经读完，返回0
                    l = inStream.Read(buffer, 0, buffer.Length);
                    //将数据写入流，从下标0开始，每次取1个字节写入流
                    if (l > 0) outStream.Write(buffer, 0, l);
                } while (l > 0);
                //写入完毕，返回true
                value = true;
            }
            finally
            {
                //关闭字节流，释放资源
                if (outStream != null) outStream.Close();
                if (inStream != null) inStream.Close();
            }
            return value;
        }

        /// <summary>
        /// 获取文件MD5值
        /// </summary>
        /// <param name="fileName">文件绝对路径</param>
        /// <returns>MD5值</returns>
        public static string GetMD5HashFromFile(string fileName)
        {
            try
            {
                FileStream file = new FileStream(fileName, System.IO.FileMode.Open);
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
            }
        }
        /// <summary>
        /// 判断文件路径是否存在
        /// </summary>
        /// <param name="filePath">相对路径</param>
        /// <returns>文件是否存在</returns>
        public static bool FileExist(String filePath)
        {
            return System.IO.File.Exists(filePath);
        }

        /// <summary>
        /// 获取文件绝对路径
        /// </summary>
        /// <param name="filePath">相对路径</param>
        /// <returns>文件绝对路径</returns>
        public static String getAbsolutePath(String filePath)
        {
            //文件存在时有绝对路径
            if (System.IO.File.Exists(filePath))
            {
                return System.AppDomain.CurrentDomain.BaseDirectory + filePath;
            }
            //文件不存在
            else
            {
                return "文件不存在";
            }
        }

        /// <summary>
        /// 获取文件名，不带后缀
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static String getFileName(String filePath)
        {
            return Path.GetFileNameWithoutExtension(filePath);
        }

        /// <summary>
        /// 获取文件后缀名
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static String getExtensionName(String filePath)
        {
            return Path.GetExtension(filePath);
        }
        /// <summary>
        /// 获取文件根目录
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static String GetPathRoot(String filePath)
        {
            return Path.GetPathRoot(filePath);
        }
        /// <summary>
        /// 获取文件所在目录
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static String GetDirectoryName(String filePath)
        {
            return Path.GetDirectoryName(filePath);
        }
        /// <summary>
        /// 根据文件格式读取内容
        /// </summary>
        /// <param name="filePath">路径</param>
        /// <param name="fileType">格式</param>
        /// <returns></returns>
        public static string ReadFile(string filePath, string fileType)
        {
            try
            {
                string content = "文件格式不支持检索";
                filePath = HttpContext.Current.Server.MapPath(filePath);
                if (fileType == ".txt")
                {
                    StreamReader sr = new StreamReader(filePath);
                    content = sr.ReadToEnd().ToString();
                    sr.Close();
                }
                return content;
            }
            catch (Exception e)
            {
                return "对不起，本文没有发现！可能是从服务器上删除的。";
            }
        }
        /// <summary>
        /// 读取文本文档内容
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static String ReadTxtFile(string filePath)
        {
            return System.IO.File.ReadAllText(filePath);
        }

        /// <summary>
        /// 读csv转至List<String>
        /// </summary>
        /// <param name="strpath"></param>
        /// <returns></returns>
        public static List<String> readCsvTxtToList(string strpath)
        {
            List<String> csv解析 = new List<string>();
            string strline;
            StreamReader streamReader = new System.IO.StreamReader(strpath);
            while ((strline = streamReader.ReadLine()) != null)
            {
                csv解析.Add(strline);
            }
            return csv解析;
        }

        public static String ConvertDocToDocx(string path)
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();

            if (path.ToLower().EndsWith(".doc"))
            {
                var sourceFile = new FileInfo(path);
                var document = word.Documents.Open(sourceFile.FullName);

                string newFileName = sourceFile.FullName.Replace(".doc", ".docx");
                document.SaveAs2(newFileName, WdSaveFormat.wdFormatXMLDocument,
                                 CompatibilityMode: WdCompatibilityMode.wdWord2010);

                word.ActiveDocument.Close();
                word.Quit();

                File.Delete(path);
                return newFileName;
            }
            else
            {
                return path;
            }
        }

        /// <summary>
        /// 转换excel 成PDF文档
        /// </summary>
        /// <param name="_lstrInputFile">原文件路径</param>
        /// <param name="_lstrOutFile">pdf文件输出路径</param>
        /// <returns>true 成功</returns>
        public static Boolean ConverterToPdf(string _lstrInputFile, string _lstrOutFile)
        {
            Microsoft.Office.Interop.Excel.Application lobjExcelApp = null;
            Microsoft.Office.Interop.Excel.Workbooks lobjExcelWorkBooks = null;
            Microsoft.Office.Interop.Excel.Workbook lobjExcelWorkBook = null;
            string lstrTemp = string.Empty;
            object lobjMissing = System.Reflection.Missing.Value;
            try
            {
                lobjExcelApp = new Microsoft.Office.Interop.Excel.Application();
                lobjExcelApp.Visible = true;
                lobjExcelWorkBooks = lobjExcelApp.Workbooks;
                lobjExcelWorkBook = lobjExcelWorkBooks.Open(_lstrInputFile, true, true, lobjMissing, lobjMissing, lobjMissing, true,
                  lobjMissing, lobjMissing, lobjMissing, lobjMissing, lobjMissing, false, lobjMissing, lobjMissing);
                //Microsoft.Office.Interop.Excel 12.0.0.0之后才有这函数     
                lstrTemp = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".xls" + (lobjExcelWorkBook.HasVBProject ? 'm' : 'x');
                //lstrTemp = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".xls";
                //lobjExcelWorkBook.SaveAs(lstrTemp, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel4Workbook, Type.Missing, Type.Missing, Type.Missing, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing,
                //  false, Type.Missing, Type.Missing, Type.Missing);
                //输出为PDF 第一个选项指定转出为PDF,还可以指定为XPS格式
                lobjExcelWorkBook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, _lstrOutFile, Microsoft.Office.Interop.Excel.XlFixedFormatQuality.xlQualityStandard, Type.Missing, false, Type.Missing, Type.Missing, false, Type.Missing);
                lobjExcelWorkBooks.Close();
                lobjExcelApp.Quit();
            }
            catch (Exception ex)
            {
                //其他日志操作；
                return false;
            }
            return true;
        }

        /// <summary>
        /// 将json转换为DataTable
        /// </summary>
        /// <param name="strJson">得到的json</param>
        /// <returns></returns>
        public static void JsonToDT(String fileName, String strJson)
        {
            // 1、Create empty workbook
            Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();

            Aspose.Cells.Worksheet workSheet = workbook.Worksheets[0];
            
            // 2、Get Cells
            Aspose.Cells.Cells cells = workSheet.Cells;

            // 3、Set JsonLayoutOptions
            Aspose.Cells.Utility.JsonLayoutOptions importOptions = new Aspose.Cells.Utility.JsonLayoutOptions();
            importOptions.ConvertNumericOrDate = true;
            importOptions.ArrayAsTable = true;
            //  列名是否显示
            //importOptions.IgnoreArrayTitle = true;
            //importOptions.IgnoreObjectTitle = true;
            //// 設置樣式
            //CellsFactory factory = new CellsFactory();
            //Aspose.Cells.Style style = factory.CreateStyle();
            //style.HorizontalAlignment = TextAlignmentType.Center;
            //style.Font.Color = System.Drawing.Color.BlueViolet;
            //style.Font.IsBold = true;
            //importOptions.TitleStyle = style;

            // 4、
            Aspose.Cells.Utility.JsonUtility.ImportData(strJson, cells, 0, 0, importOptions);
            //Aspose.Cells.DataSorter dataSorter = workbook.DataSorter;
            
            // 5、Save Workbook
            workbook.Save(fileName, SaveFormat.Auto);
        }

        /// <summary>
        /// 获取到本地的Json文件并且解析返回对应的json字符串
        /// </summary>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public static String GetJsonFile(string filepath)
        {
            String json = String.Empty;
            using (FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate, System.IO.FileAccess.Read, FileShare.Read))
            {
                using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
                {
                    json = sr.ReadToEnd().ToString();
                }
            }
            return json;
        }
    }
}